package com.daou.smartpush.service.license;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daou.smartpush.common.Config;
import com.daou.smartpush.common.util.DateConverter;
import com.daou.smartpush.domain.company.Company;
import com.daou.smartpush.domain.license.License;
import com.daou.smartpush.model.license.LicenseModel;
import com.daou.smartpush.repository.company.CompanyRepository;
import com.daou.smartpush.repository.license.LicenseRepository;

/**
 * License Service Class
 * 
 * @author seungkyupark84
 * 
 */
@Service
public class LicenseService {

    @Autowired
    LicenseRepository licenseRepository;

    @Autowired
    CompanyRepository companyRepository;

    /**
     * License 파일 생성 처리 메서드
     * 
     * @param uniqueId
     * @param maxDevice
     * @param expireDate
     * @return
     */
    public License registOrUpdateLicense(LicenseModel licenseModel) {
        License tempLicense;
        boolean isSuccess = true;
        License license = null;
        
        Company company = companyRepository.findOne(licenseModel.getCompanySeq());

        if (licenseModel.getId() != null) {
        	license = licenseRepository.findOne(licenseModel.getId());
        	
        	license.setHostId(licenseModel.getHostId());
        	license.setpName(licenseModel.getpName());
        	license.setVersion(licenseModel.getVersion());
        	license.setUnLimit(licenseModel.getUnLimit());
        	license.setMaxDeviceCnt(licenseModel.getMaxDeviceCnt());
        	license.setExpiredDate(licenseModel.getExpiredDate());
		}else {
			license = new License(licenseModel);
			license.setCompany(company);
		}
        
        isSuccess = createLicense(license);

        if (isSuccess == true) {
            tempLicense = licenseRepository.save(license);
        } else {
            tempLicense = null;
        }

        return tempLicense;
    }

    /**
     * 실제 License 파일 생성 메서드
     * 
     * @param license
     * @return
     */
    private boolean createLicense(License license) {
        boolean isSuccess = true;

        String encrypt = null;

        
        String tempDate = DateConverter.getDateToString(license.getExpiredDate(), Config.DATE_FORMAT_NONE);
        String message = license.getHostId() + "|" + license.getUnLimit() + "|" + license.getMaxDeviceCnt() + "|"
                + tempDate;
        String path = Config.filePath
                + license.getCompany().getCompanySeq() + "/" + license.getHostId().replaceAll(":", "");
        
        System.out.println(path);
        try {
            // 암호화
            encrypt = AES256.encrypt(message);

            // 파일 생성
            File f = new File(path);
            
            // 디렉터리 생성
            if (!f.exists()) {
                f.mkdirs();
                System.out.println("=======File Suceess MKDIR========");
            }

            if (!f.isFile()) {
                f.createNewFile();
            }

            BufferedWriter out = new BufferedWriter(new FileWriter(path + "/License.lic"));
            out.write(encrypt);
            out.close();
            System.out.println("=======File Suceess Create========");
        } catch (Exception e) {
        	System.out.println(e.getMessage());
            isSuccess = false;
        }

        return isSuccess;
    }

    /**
     * 파일 삭제 매서드
     * 
     * @param id
     * @param hostId
     * @return
     */
    private boolean deleteLicenseFile(Long id, String hostId) {
        boolean isSuccess = false;

        String path = Config.filePath + id + "/"
                + hostId.replaceAll(":", "");

        File f = new File(path + "/License.lic");

        if (f.delete()) {
            File d = new File(path);

            if (d.delete()) {
                isSuccess = true;
            }
        }

        return isSuccess;
    }

    /**
     * 모든 License 정보 추출 메서드
     * 
     * @return
     */
    public List<License> getAllLicense() {
        List<License> results = licenseRepository.findAll();
        return results;
    }

    /**
     * 특정 License 정보 추출하여 LicenseModel로 반환 하는 메서드
     * 
     * @param id
     * @return
     */
    public LicenseModel getLicenseInfo(Long id) {
        LicenseModel licenseModel = null;
        License license = licenseRepository.findOne(id);

        if (license != null) {
            licenseModel = new LicenseModel(license);
        }

        return licenseModel;
    }

    public boolean deleteLicense(Long id) {
        boolean result = false;
        License license = licenseRepository.findOne(id);

        if (deleteLicenseFile(license.getCompany().getCompanySeq(), license.getHostId())) {
            try {
                licenseRepository.delete(license.getId());
                result = true;
            } catch (Exception e) {

            }
        }
        return result;
    }

	public License selectLicenseByHost(String host) {
		License license = licenseRepository.findByHostId(host);
		return license;
	}
}
